/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_port/link_info.h"

namespace dev {

bool NetworkPort_LinkInfo::update_link_status_by_ncsi(uint8_t port_id) {
    ncsi_link_status_info_t link_status = {};
    bool ret = m_ncsi_over_mctp_huawei->get_link_status(DEFAULT_PACKAGE_ID, port_id, &link_status);
    if (!ret) {
        elog("Error: Failed to update link status");
        LinkStatus.set_value(255);  // 无效值
        SpeedMbps.set_value(0);
        FullDuplex.set_value(false);
        return false;
    }
    LinkStatus.set_value(link_status.link_status);
    SpeedMbps.set_value(link_status.speed_mbps);
    FullDuplex.set_value(link_status.full_duplex ? true : false);
    return true;
}

void NetworkPort_LinkInfo::start_ncsi_update_task_huawei(ncsi_over_mctp_hw_ptr ncsi_over_mctp,
                                                         mc::milliseconds      interval,
                                                         uint8_t               port_id) {
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        update_link_status_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_LinkInfo::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        m_ncsi_timer = nullptr;
    }
    if (m_ncsi_over_mctp_huawei) {
        m_ncsi_over_mctp_huawei = nullptr;
    }
}

uint8_t NetworkPort_LinkInfo::convert_link_status(uint8_t link_status) {
    // 0-DOWN, 1-UP, 255-无效值
    switch (link_status) {
    case 0x00:
        return 0;  // DOWN
    case 0x01:
        return 1;  // UP
    default:
        return 255;  // 无效值
    }
}

bool NetworkPort_LinkInfo::update_link_status_by_smbus(uint8_t port_id) {
    // 使用静态变量缓存，减少频繁创建
    static mc::mutable_dict request_template{{"opcode", 0x0403}};
    auto rsp = m_smbus_obj->send_request(request_template);
    if (rsp.empty()) { // 如果smbus校验未通过，返回值为空，需要校验返回值
        elog("Error: failed to get link status by smbus");
        return false;
    }
    std::vector<uint8_t> rsp_data;
    try {
        for (size_t i = 0; i < rsp.size(); i++) {
            uint8_t link_status = rsp[i];
            rsp_data.push_back(link_status);
        }
    } catch (const std::exception& e) {
        elog("Error: Failed to parse link status by smbus, exception: ${exception}",
             ("exception", e.what()));
        return false;
    }

    uint8_t link_status = convert_link_status(rsp_data[port_id]);
    // link_status 已经是数值类型：0-DOWN, 1-UP, 255-无效值
    LinkStatus.set_value(link_status);
    return true;
}

void NetworkPort_LinkInfo::start_smbus_update_task(smbus_obj_ptr    smbus_obj,
                                                   mc::milliseconds interval, uint8_t port_id) {
    if (!smbus_obj) {
        elog("Error: smbus_obj is not initialized");
        return;
    }
    m_smbus_obj   = smbus_obj;
    m_smbus_timer = new mc::core::timer(this);
    m_smbus_timer->timeout.connect([this, port_id]() {
        update_link_status_by_smbus(port_id);
    });
    m_smbus_timer->set_single_shot(false);
    m_smbus_timer->start(interval);
}

void NetworkPort_LinkInfo::stop_smbus_update_task() {
    if (m_smbus_timer) {
        m_smbus_timer->stop();
        
        m_smbus_timer = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort_LinkInfo)